<template>
  <section class="table-wrap">
    <div class="action-wrap">
      <el-form ref="paramRef" :model="params" inline>
        <el-form-item label="名称：" prop="name">
          <el-input
            v-model="params.name"
            placeholder="请输入名称"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableList" style="width: 100%">
      <el-table-column prop="cover" label="封面" align="center" />
      <el-table-column prop="name" label="名称" align="center" />
      <el-table-column label="分类一" align="center">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.category1Id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类二" align="center">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.category2Id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="docCount" label="文档数" align="center" />
      <el-table-column prop="viewCount" label="阅读数" align="center" />
      <el-table-column prop="voteCount" label="点赞数" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleToDoc(scope.row)">文档管理</el-button>
          <el-button type="warning" link @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination ref="pageRef" :total="total" @query="queryHandler" />
    <Dialog
      :visible="visible"
      title="电子书表单"
      :width="700"
      @cancel="handleCancel"
      @confirm="handleConfirm"
    >
      <el-form :model="form" label-width="120" style="max-width: 600px">
        <el-form-item label="封面">
          <el-input v-model="form.cover" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name" :maxlength="32" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader
            v-model="categoryValue"
            :options="categoryTree"
            :props="{ label: 'name', value: 'id' }"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="文档数">
          <el-input v-model="form.docCount" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="阅读数">
          <el-input v-model="form.viewCount" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input v-model="form.voteCount" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </section>
</template>

<script setup>
import Pagination from '@/components/pagination/Pagination.vue'
import { getEbookList, saveEbook, deleteEbook } from '../../api/ebook'
import Dialog from '@/components/dialog/Dialog.vue'
import { getCategoryAll } from '../../api/category'
import { array2Tree, copy } from '@/utils/index.js'
import { useRouter } from 'vue-router'

const pageRef = ref()
const total = ref(0)
const tableList = ref([])
const visible = ref(false)
const form = ref({})
const paramRef = ref()
const params = ref({
  name: ''
})
const categoryList = ref([])
const categoryTree = ref([])
const categoryValue = ref([])

const router = useRouter()

onMounted(() => {
  getCategory()
})

const handleToDoc = (row) => {
  router.push({ path: '/doc', query: { ebookId: row.id } })
}

const getCategoryName = (id) => {
  for (let category of categoryList.value) {
    if (category.id === id) return category.name
  }
  return ''
}

const getCategory = async () => {
  const { success, data, message } = await getCategoryAll()
  if (success) {
    categoryList.value = copy(data)
    categoryTree.value = array2Tree(data, 0)
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const handleCancel = () => {
  visible.value = false
  categoryValue.value = []
}

const handleConfirm = () => {
  handleSave()
}

const handleAdd = () => {
  form.value = {}
  visible.value = true
}

const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row))
  categoryValue.value = [form.value.category1Id, form.value.category2Id]
  visible.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该条数据？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { success, message } = await deleteEbook(id)
      if (success) {
        pageRef.value.query()
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } else {
        ElMessage({
          type: 'error',
          message
        })
      }
    })
    .catch(() => {})
}

const handleSave = async () => {
  const category1Id = categoryValue.value.length ? categoryValue.value[0] : ''
  const category2Id = categoryValue.value.length ? categoryValue.value[1] : ''

  const { success, message } = await saveEbook({
    ...form.value,
    category1Id,
    category2Id
  })
  if (success) {
    visible.value = false
    categoryValue.value = []
    pageRef.value.query()
    ElMessage({
      type: 'success',
      message: '保存成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const getList = async (current, pageSize) => {
  const { success, data, message } = await getEbookList({
    name: params.value.name,
    page: current,
    size: pageSize
  })

  if (success) {
    tableList.value = data.list
    total.value = data.total
  } else {
    ElMessage({
      type: 'error',
      message
    })
  }
}

const handleReset = () => {
  paramRef.value.resetFields()
  pageRef.value.resetQuery()
}

const handleQuery = () => {
  pageRef.value.resetQuery()
}

const queryHandler = (current, pageSize) => {
  getList(current, pageSize)
}
</script>

<style lang="scss" scoped></style>
../../api/ebook
